﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

using WorkStation.Frameworks.Core.Reflection;

namespace WorkStation.Frameworks.Configuration.Elements
{
    [Serializable]
    public abstract class BaseInstanceConfiguration : BaseConfiguration
    {
        [XmlAttribute(AttributeName = "type")]
        public string Type { get; set; }

        /// <summary>
        /// * 根据当前Type属性生成对象
        /// </summary>
        /// <returns></returns>
        public virtual object CreateInstance()
        {
            return BaseInstanceConfiguration.CreateInstance(this.Type);
        }

        /// <summary>
        /// * 根据当前Type属性生成对象
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <returns></returns>
        public virtual T CreateInstance<T>() where T : class
        {
            return BaseInstanceConfiguration.CreateInstance(this.Type) as T;
        }

        /// <summary>
        /// * 根据TypeString生成对象
        /// </summary>
        /// <param name="typeString"></param>
        /// <returns></returns>
        public static object CreateInstance(string typeString)
        {
            List<string> types = typeString.Split(',').ToList();

            if (types.Count == 2)
            {
                types.ForEach(v => v.Trim());

                return ClassLibraryObjectFactory.CreateObject<object>(types[0], types[1]);
            }
            else
            {
                return ClassLibraryObjectFactory.CreateObject<object>(types[0]);
            }
        }
    }
}
